/*
 * @FilePath: /tads/server/initialize/init.go
 * @Author: wnina0x0
 * @Date: 2025-04-11 15:19:03
 * @Description:
 *
 * 版权信息 : 2025 by wnina0x0, All Rights Reserved.
 */
package initialize

import (
	"fmt"
	"log"
	"os"
	"tads/server/common/database"
	"tads/server/config"
	"tads/server/core"
	"tads/server/global"

	"github.com/golang-jwt/jwt/v5"
	"gopkg.in/yaml.v2"
)

type ParseYaml struct {
	server config.Server
}

func init() {
	p := ParseYaml{}
	p.InitJwt()
	p.ParseConfig()
	p.InitDb()
	p.InitSystem()
	p.InitLog()
}

func (p *ParseYaml) InitSystem() {
	global.TADS_PORT = &p.server.System.Port
}

func (p *ParseYaml) InitDb() {
	global.TADS_DBNAME = &p.server.Postgres.DbName
	global.TADS_DBTYPE = &p.server.System.DbType
	global.TADS_DSN = p.server.Postgres.Dsn()
	global.TADS_DB = Gorm()
	database.SetUp()

}

func (p *ParseYaml) InitJwt() {
	global.TADS_PARSER_OPTION = jwt.WithExpirationRequired()
}

func (p *ParseYaml) InitLog() {
	config := core.Config{
		EnableConsole: true,
		EnableFile:    false,
		EnableDB:      true,
		Color:         true,
		FileLocation:  "./logs/app.log",
	}
	logger, err := core.NewLogger(config)
	if err != nil {
		log.Printf("Log初始化失败:%s\n", err.Error())
		os.Exit(-1)
	}
	global.TADS_LOG = logger

}

func (p *ParseYaml) ParseConfig() {
	server := config.Server{}
	file, err := os.Open("config.dev.yaml")
	if err != nil {
		fmt.Printf("error: %v\n", err)
		return
	}
	defer file.Close()
	decoder := yaml.NewDecoder(file)
	err = decoder.Decode(&server)
	if err != nil {
		fmt.Printf("error: %v\n", err)
		return
	}
	p.server = server
}

func InitConfig() {
	log.Printf("初始化成功\n")
}
